<!--  -->
<template>
  <div
    :class="['product-detail',flag?'':'',tabIndex==1&&commentList.length!=0?'product-detail-h-100':'']"
  >
    <Nav title="产品详情">
      <template v-slot:left>
        <span class="back-icon" @click="$router.back()"></span>
      </template>
    </Nav>
    <!-- 轮播图 -->
    <swiper class="swiper" :options="swiperOption" v-if="swiperSlides.length!=0">
      <swiper-slide v-for="(slide, index) in swiperSlides" :key="index">
        <img :src="slide" alt @click="previewImg(swiperSlides,index)" />
      </swiper-slide>
      <div class="swiper-pagination" slot="pagination"></div>
    </swiper>
    <div class="swiper" v-else></div>
    <div class="product-info flex aligin-center">
      <div class="flex-1 info flex justify-between aligin-center">
        <span class="f-16 color-red">
          ￥
          <span class="f-22 color-red f-bold">{{productData.goods.price}}</span>
          <span class="f-12 color-gray discount-through">￥{{productData.goods.offer_price}}</span>
        </span>
      </div>
      <div class="rate f-12 color-white flex justify-center aligin-center" @click="share">
        <span class="share-icon"></span>
        <span>分享</span>
      </div>
    </div>
    <div class="tag-wrap flex">
      <template v-for="(item,index) in productData.tag">
        <span class="tag" :key="index">{{item}}</span>
      </template>
    </div>
    <div class="action">{{productData.name}}</div>
    <!-- 进度条 -->
    <div class="progress-wrapper mt-16" v-if="productData.open_status!=2">
      <div class="progress" :style="{width:productData.progress+'%'}"></div>
    </div>
    <div class="flex progress-info justify-between aligin-center f-14 mt-6" v-if="productData.open_status!=2">
      <div class="f-12">本期参与人数{{productData.current}}人</div>
      <div class="f-12">还剩{{productData.surplus}}个名额</div>
    </div>
    <div class="progress-wrapper mt-16" v-if="productData.open_status==2">
      <div class="progress" style="width:100%"></div>
    </div>
    <div class="action-close" v-if="productData.open_status==2">活动已结束</div>
    <div class="divide-line"></div>
    <div class="menu-item flex justify-between aligin-center" @click="showRule">
      <span class="label">活动玩法</span>
      <span class="menu-content">未中奖退款，参与即送0元购次数</span>
      <span class="arrow-right"></span>
    </div>
    <div class="divide-line"></div>
    <div class="menu-item flex justify-between aligin-center" @click="showPhone">
      <span class="label">我的号码</span>
      <span class="menu-content">点击查看</span>
      <span class="arrow-right"></span>
    </div>
    <div class="divide-line"></div>
    <div class="menu-item flex justify-between aligin-center" @click="showHistroy">
      <span class="label">活动记录</span>
      <span class="menu-content">{{productData.issue_id}}期,查看往期天选之人</span>
      <span class="arrow-right"></span>
    </div>
    <div class="divide-line"></div>
    <div id="tabDetail"></div>
    <div
      class="flex justify-between aligin-center"
      style=" background: #fff;"
      :class="isSticky?'sticky':''"
    >
      <div class="tab-container">
        <div class="menu-title">宝贝详情</div>
      </div>
    </div>
    <div :class="isSticky?'pt-64':''" class="height-full">
      <template v-if="tabIndex==0">
        <div ref="htmlParent" class="html-parent" v-html="productData.description"></div>
      </template>
    </div>

    <BottomBar
      v-show="!flag"
      :isCollection.sync="isCollection"
      @orderConfirm="orderConfirm"
      @toService="showTel"
    ></BottomBar>
    <div class="mask-info" v-if="showMask">
      <div class="J-weixin-tip weixin-tip">
        <div class="weixin-tip-content">请在菜单中选择分享</div>
      </div>
      <div class="btn flex justify-center aligin-center" @click="showMask=false">我知道了</div>
    </div>
    <!-- 选择产品参数 -->
    <ProductParams
      ref="productParams"
      class="scroll-wrapper"
      type="shoppingCar"
      :flag.sync="flag"
      :discount="true"
      :is_norequiremoney="productData.is_norequiremoney"
      :m_id="productData.m_id"
      :givePower.sync="productData.give_power"
      :power.sync="productData.power"
      :current.sync="productData.current"
      :progress.sync="productData.progress"
      :productOption.sync="productOption"
      :initPic.sync="initPic"
      :c_selectOption.sync="c_selectOption"
      :sku.sync="sku"
      :limit.sync="productData.limit"
      @submit="submit"
      @closeDialog="closeDialog"
      @addShoppingCar="addShoppingCar"
      @optionSelected="optionSelected"
    ></ProductParams>
    <action-histroy
      ref="actionHistroy"
      @closeDialog="closeHistroyDialog"
      :flag="actionHistroyFlag"
      :activityId="productData.activity_id"
    ></action-histroy>
    <Phone
      ref="phone"
      @closeDialog="closephoneDialog"
      :flag="actionPhoneFlag"
      :activityKey="productData.key"
    ></Phone>
    <!-- 中奖规则 -->
    <Rule
      ref="rule"
      :flag.sync="ruleFlag"
      :activityId="productData.activity_id"
      @closeDialog="ruleFlag=false"
    ></Rule>
  </div>
</template>

<script>
import Nav from '../../components/Nav'
import Rule from '../../components/Rule'
import { ImagePreview } from 'vant'
import ProductParams from '../../components/ProductParams'
import {
  discount_detail,
  productDetail,
  productSku,
  orderCreate,
  productEvaluate,
  weLogin,
  cart_store
} from '../../api/api'
import TabCommon from '../../components/TabCommon'
import BottomBar from '../../components/BottomBar'
import Comment from '../../components/Comment'
import ActionHistroy from '../../components/ActionHistroy'
import Phone from '../../components/phone'
import Page from '../../mixin/page'
import { fromEvent, from, merge, empty, of, concat } from 'rxjs'
import {
  map,
  filter,
  exhaustMap,
  debounceTime,
  switchMap,
  throttleTime,
  tap
} from 'rxjs/operators'
export default {
  mixins: [Page],
  components: {
    Nav,
    ProductParams,
    TabCommon,
    BottomBar,
    Comment,
    ActionHistroy,
    Phone,
    Rule
  },
  data() {
    return {
      showMask: false,
      scrollTop: '',
      productData: { key: '', goods: {}, merchant: {}, power: 10 }, //产品详情
      productOption: [], //产品参数
      c_selectOption: [], //参数规格
      sku: [], //匹配规则？
      initPic: '', //初始化图片
      swiperOption: {
        loop: true,
        autoplay: true, //等同于以下设置
        pagination: {
          el: '.swiper-pagination'
        }
      }, //轮播图配置
      swiperSlides: [], //轮播图
      flag: false, //选取产品参数组件flag
      tabIndex: 0,
      isFirst: true,
      isSticky: false,
      actionHistroyFlag: false,
      actionPhoneFlag: false,
      ruleFlag: false,
      tabs: ['宝贝详情'],
      payFlag: false, //支付flag
      isCollection: false, //是否收藏
      commentList: [] //品论列表
    }
  },
  domStreams: ['tabChange$'],
  subscriptions() {
    let subscribtion = this.initRxjs()
    return {
      observabelProductList: subscribtion
    }
  },
  computed: {},
  watch: {},
  methods: {
    showRule() {
      this.ruleFlag = true
      this.$refs.rule.request()
    },
    closephoneDialog() {
      this.actionPhoneFlag = false
    },
    closeHistroyDialog() {
      this.actionHistroyFlag = false
    },
    showPhone() {
      this.$refs.phone.request()
      this.actionPhoneFlag = true
    },
    showHistroy() {
      this.$refs.actionHistroy.request()
      this.actionHistroyFlag = true
    },
    previewImg(url, index) {
      console.log('url', url)
      ImagePreview({ images: url, startPosition: index })
    },
    toDetail() {
      if (this.$route.query.pid) {
        this.$router.replace({
          name: 'detail',
          params: { id: this.$route.params.id },
          query: { pid: this.$route.query.pid }
        })
      } else {
        this.$router.replace({
          name: 'detail',
          params: { id: this.$route.params.id }
        })
      }
    },
    _shareConfig(jsk) {
      wx.config(jsk)
      wx.ready(() => {
        wx.updateTimelineShareData({
          title: this.productData.name, // 分享标题
          link:
            window.location.origin +
            window.location.pathname +
            '?pid=' +
            this.productData.uid, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: this.swiperSlides[0], // 分享图标
          success: function() {
            console.log(
              'success',
              window.location.origin + window.location.pathname
            )
          },
          fail: function(e) {
            console.log(
              'fail',
              window.location.origin + window.location.pathname
            )
            console.log(e)
          }
        })
        wx.updateAppMessageShareData({
          title: this.productData.name, // 分享标题
          link:
            window.location.origin +
            window.location.pathname +
            '?pid=' +
            this.productData.uid, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          desc: this.productData.share_name || '兰溪官方特色购物平台。', // 分享描述
          imgUrl: this.swiperSlides[0], // 分享图标
          success: function() {
            console.log(
              'success',
              window.location.origin + window.location.pathname
            )
          },
          fail: function(e) {
            console.log(
              'fail',
              window.location.origin + window.location.pathname
            )
            console.log(e)
          }
        })
      })
      wx.error(res => {
        // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
      })
    },
    share() {
      // 分享
      var ua = navigator.userAgent.toLowerCase()
      var isWeixin = ua.indexOf('micromessenger') != -1
      if (isWeixin) {
        this.showMask = true
      } else {
        this.$copyText(
          window.location.origin +
            window.location.pathname +
            '?pid=' +
            this.productData.uid
        ).then(
          e => {
            this.$toast('复制成功！')
          },
          e => {
            this.$notify(e)
          }
        )
      }
    },
    showTel() {
      window.location.href = 'tel://' + this.productData.merchant.m_phone
    },
    getTabTop() {
      return document.getElementById('tabDetail').offsetTop
    },
    initRxjs() {
      //滚动事件
      let scroll = fromEvent(window, 'scroll').pipe(
        //判断吸顶
        tap(() => {
          let top = document.getElementById('tabDetail').getBoundingClientRect()
            .top
          this.isSticky = top <= 0
        }),
        //判断是否滚动到底部
        filter(() =>
          this.isScrollEnd(document.documentElement || document.body)
        ),
        filter(() => this.tabIndex == 1),
        //判断是否还有数据未加载
        filter(this.noMoreData),
        //截流
        throttleTime(1000)
      )
      //tab 切换事件
      let tabEvent = this.tabChange$.pipe(
        //判断是否是有效切换
        filter(({ event: { msg: index } }) => {
          if (this.tabIndex != index) {
            this.tabIndex = index
            this.current_page = 0
            this.last_page = 1
            this.productList = []
            return true
          }
          return false
        }),
        filter(() => this.tabIndex == 1)
      )
      return merge(scroll, tabEvent).pipe(
        //替换
        switchMap(() =>
          productEvaluate({
            id: this.$route.params.productId,
            page: this.current_page + 1
          })
        ),
        map(this.execResult)
      )
    },
    addShoppingCar(productNumber, item) {
      cart_store({
        activity_id: this.$route.params.id,
        goods_id: this.$route.params.productId,
        sku_id: item.sku_id,
        num: productNumber
      }).then(({ data: { result } }) => {
        this.$toast(result)
        this.flag = false
      })
    },
    // 点击预购
    submit(productNumber, item) {
      this.flag = false
      this.payFlag = true
      orderCreate({
        subject: this.productData.key,
        product_id: this.productData.goods.goods_id,
        activity_id: this.$route.params.id,
        sku_id: item.sku_id,
        numbers: productNumber,
        device_code: 1
      })
        .then(res => {
          this.$router.push({
            name: 'orderDetail',
            params: { id: res.data.result.order_no }
          })
        })
        .catch(res => {
          if (res == '请先使用微信进行授权，享用更好的服务') {
            this.$dialog
              .confirm({
                message: '请先使用微信进行授权，享用更好的服务'
              })
              .then(() => {
                return weLogin({ from: 'authorization' })
              })
              .then(res => {
                window.location.href = res.data.result
              })
          }
        })
    },
    tabChange(index) {
      if (this.tabIndex != index) {
        this.tabIndex = index
        //重置
        this.current_page = 0
        this.last_page = 1
        this.loading = false
        this.commentList = []
        this._api()
      }
    },
    // 关闭产品规格对话框
    closeDialog() {
      this.flag = false
    },
    //我要预约
    orderConfirm() {
      if (this.isFirst) {
        this.selectOption()
      } else {
        let itemData = this.$refs.productParams.c_sku
        orderCreate({
          subject: this.$route.params.key,
          product_id: this.$route.params.productId,
          activity_id: this.$route.params.id,
          sku_id: itemData.sku_id,
          numbers: this.$refs.productParams.productNumber,
          device_code: 1
        })
          .then(res => {
            this.$router.push({
              name: 'orderDetail',
              params: { id: res.data.result.order_no }
            })
          })
          .catch(res => {
            if (res == '请先使用微信进行授权，享用更好的服务') {
              this.$dialog
                .confirm({
                  message: '请先使用微信进行授权，享用更好的服务'
                })
                .then(() => {
                  return weLogin({ from: 'authorization' })
                })
                .then(res => {
                  window.location.href = res.data.result
                })
            }
          })
      }
    },
    //弹出产品规格对话框
    selectOption() {
      productSku({ id: this.productData.goods.goods_id }).then(res => {
        this.productOption = res.data.result.spec
        this.sku = res.data.result.sku
        let data = res.data.result.spec.map(item => {
          return item.value[0]
        })
        this.c_selectOption = data
        this.flag = true
      })
    },
    //选择规格
    optionSelected(item) {
      //设置单选
      let index = this.c_selectOption.findIndex(_item => {
        return _item.spec_id == item.spec_id
      })
      if (index != -1) {
        this.c_selectOption.splice(index, 1, item)
      }
    }
  },
  created() {},
  mounted() {
    discount_detail({
      id: this.$route.params.id
    }).then(({ data: { result } }) => {
      this.productData = result
      this.initPic = result.goods.swiper_imgs[0]
      this.swiperSlides = result.goods.swiper_imgs
      const regex = new RegExp('<img', 'gi')
      this.$set(
        this.productData,
        'description',
        result.goods.description.replace(
          regex,
          `<img style="max-width: 100%; height: auto;display:block"`
        )
      )
      this.$nextTick(() => {
        this.scrollTop = this.getTabTop()
      })
      //微信分享配置
      if (typeof wx != 'undefined') {
        this._shareConfig(result.jsk)
      }
    })
  },
  updated() {}, //生命周期 - 更新之后
  destroyed() {
    window.onscroll = null
    clearTimeout(this.loadMoreTimer)
    this.loadMoreTimer = null
  } //生命周期 - 销毁完成
}
</script>
<style lang='less' scoped>
@import url('../../assets/style/mixin'); //引入公共css类

.product-detail /deep/ .swiper-pagination-bullet {
  border-radius: 50%;
  width: 5px;
  height: 5px;
  background: #b6b6b7;
  transition: all 0.3s ease;
}
.product-detail /deep/ .swiper-pagination-bullet-active {
  width: 23px;
  height: 5px;
  border-radius: 3px;
  .bg-1();
}
.pt-64 {
  padding-top: 64px;
}
.height-full {
  padding-bottom: 50px;
  background: #fff;
  min-height: calc(100% - 64px);
}
.sticky {
  position: fixed;
  top: 0;
  height: 64px;
  width: 100%;
  background: #fff;
  z-index: 100;
}
.color-white {
  color: #fff;
}
.product-detail-h-100 {
  height: 100%;
}
.tab-container {
  padding: 10px 20px;
  width: 50%;
  .menu-title {
    font-size: 15px;
    font-weight: bold;
  }
}
.product-detail {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding-bottom: 60px;
  height: 100%;
  box-sizing: border-box;
  background: #fff;
  z-index: 400;
  .activity-info {
    padding: 11px 12px;
    font-size: 12px;
    line-height: 16px;
    .flex-1 {
      flex: 1;
    }
    .label {
      width: 50px;
      flex-shrink: 0;
    }
    .color-red {
      color: #cc0000;
    }
    .arrow-right {
      flex-shrink: 0;
      height: 12px;
      width: 12px;
      .bg-image('../../assets/imgs/arrow-right-b');
      background-size: 100% 100%;
    }
  }
  .back-icon {
    display: inline-block;
    width: 16px;
    height: 16px;
    .bg-image('../../assets/imgs/back');
    background-size: 100% 100%;
  }
  .notice {
    display: inline-block;
    width: 17px;
    height: 17px;
    .bg-image('../../assets/imgs/notice');
    background-size: 100% 100%;
  }
  .share {
    display: inline-block;
    width: 17px;
    height: 17px;
    .bg-image('../../assets/imgs/share-product');
    background-size: 100% 100%;
  }
  .swiper {
    height: 375px;
    img {
      display: block;
      height: 100%;
      width: 100%;
      &::after {
        display: none;
      }
    }
  }
  .product-info {
    height: 35px;
    .discount-through {
      text-decoration: line-through;
    }
    .info {
      padding: 0 22px 0 17px;
      height: 100%;
    }
    .f-16 {
      font-size: 16px;
      font-weight: 500;
    }
    .rate {
      width: 67px;
      height: 23px;
      border-top-left-radius: 10px;
      border-bottom-left-radius: 10px;
      .bg-1();
      .share-icon {
        margin-right: 4px;
        width: 16px;
        height: 14px;
        background: url('../../assets/imgs/share-icon.png');
        background-size: 100% 100%;
      }
    }
  }
  .tag-wrap {
    margin-left: 16px;
    margin-top: 13px;
    .tag {
      margin-right: 10px;
      padding: 7px 8px;
      font-size: 10px;
      background: rgba(255, 241, 242, 1);
      border-radius: 3px;
    }
  }
  .action {
    margin: 19px 20px 0 15px;
    font-size: 14px;
    line-height: 19px;
  }
  .progress-wrapper {
    margin: 17px 20px 0 15px;
    position: relative;
    height: 10px;
    background: #eee;
    border-radius: 3px;
    .progress-number {
      position: absolute;
      left: 50%;
      top: 0;
      transform: translateX(-50%);
      font-size: 10px;
      color: #fff;
    }
  }
  .progress-info {
    margin: 12px 20px 20px 15px;
    color: #f8597f;
  }
  .progress {
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    border-radius: 3px;
    .bg-1();
  }
  .action-close{
    text-align: center;
    margin: 5px 0;
    font-size: 14px;
    color:rgba(232,48,56,1);
  }
  .menu-item {
    padding: 12px 16px;
    font-size: 11px;
    .label {
      color: #bcbcbc;
    }
    .menu-content {
      margin: 0 auto 0 13px;
    }
    .arrow-right {
      width: 11px;
      height: 11px;
      background: url('../../assets/imgs/arrow-right-b@3x.png');
      background-size: 100% 100%;
    }
  }
  .other {
    padding-bottom: 14px;
    width: 306px;
  }
  .product-name {
    padding: 7px 17px 0;
    line-height: 19px;
  }
  .address {
    padding: 12px 12px;
    .height-100 {
      width: 30px;
      height: 100%;
    }
    .line-height-18 {
      line-height: 18px;
    }
  }
  .arrow-right {
    height: 12px;
    width: 12px;
    .bg-image('../../assets/imgs/arrow-right-b');
    background-size: 100% 100%;
  }
  .shop {
    padding: 0 16px;
    height: 59px;
    background: #fff;
    img {
      flex-shrink: 0;
      height: 40px;
      width: 40px;
      border-radius: 50%;
    }
    .z-btn {
      flex-shrink: 0;
      height: 25px;
      width: 55px;
      .bg-1();
    }
  }

  .scroll-wrap {
    padding-bottom: 49px;
    height: calc(100% - 60px);
    overflow: hidden;
  }
  .loading-bottom {
    width: 100%;
    text-align: center;
  }
}
.modal-open {
  position: fixed;
  width: 100%;
}
.mask-info {
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background: rgba(0, 0, 0, 0.6);
  z-index: 600;
}
.btn {
  color: #fff;
  margin: 10px auto;
  width: 70px;
  height: 25px;
  border-radius: 5px;
  border: 1px dashed #fff;
}
.weixin-tip-content {
  font-size: 16px;
  letter-spacing: 5px;
  font-weight: bold;
  line-height: 20px;
}
.weixin-tip {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #fff;
  width: 265px;
  padding: 55px 0 0;
  margin: 0 auto;
  text-align: center;
  background: url()
    no-repeat right top;
  background-size: 45px 68px;
}

.weixin-tip-img {
  padding: 110px 0 0;
}

.weixin-tip-img::after {
  display: block;
  margin: 15px auto;
  content: ' ';
  background-size: cover;
}
</style>